import { ref, reactive, unref } from "vue";
import type { Ref } from "vue";
function useTable<P, R extends { list: any; total: number }>(api: (data?: P) => Promise<any>, params?: P) {
	let tableList: Ref<R["list"]> = ref([]);
	// 分页器
	let pagination = reactive({
		currentPage: 1, //当前页
		pageSize: 10, //当前页数据条数
		total: 0,
	});

  async function fetchData(id?: number) {
    let unrefParams = {} as any; //这里的any只约束自身的类型，不影响参数的类型
    for (let key in params) {
      unrefParams[key] = unref(params[key]);
    }
    let adminList = await api({
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...unrefParams,
    });
    tableList.value = adminList.list;
    pagination.total = adminList.total;
  }
  fetchData();
  // 每页数据条数更改
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchData();
  };
  // 当前页切换
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchData();
  };
  return {
    tableList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    fetchData,
  };
}
export default useTable;
